<template>
  <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'"
    v-loading="loading">
    <el-form-item v-for="(model, index) in dataForm.models" :label="model.deptId==='0'?'默认流程':'规则' + index" :key="index"
      :prop="'models.' + index + '.procKey'">
      <el-row :gutter="24">
        <el-col :span="8" v-if="model.deptId!=='0'">
          <uni-tree-select v-model="model.deptId" ref="treeSelectDept" :selectParams="selectParams" :treeParams="treeParams"
            :data="deptList" />
        </el-col>
        <el-col :span="8">
          <!-- <el-select v-model="model.procKey" filterable placeholder="请选择流程" @change="(key)=>{processChange(key,model)}">
            <el-option v-for="item in processData" :key="item.key" :label="item.name" :value="item.key">
            </el-option>
          </el-select> -->
          <el-input v-model="model.procName" placeholder="请选择" readonly>
            <el-button slot="append" icon="el-icon-search" @click.stop="show(model)"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4" v-if="model.deptId!=='0'">
          <el-button @click.prevent="removeModel(model)">删除</el-button>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item>
      <el-button @click="addModel">新增规则</el-button>
      <process v-if="processVisible" ref="process1" @backFun="backFun" :initDataForm="{}" :multiple="false" :width="'300'"></process>
    </el-form-item>
  </el-form>
</template>

<script>
import debounce from 'lodash/debounce'
import process from '@/components/uni-bpm-process'
export default {
  components: { process },
  data () {
    return {
      processVisible: false,
      loading: true,
      formId: '',
      // 表单内容
      dataForm: {
        models: [{
          id: '',
          deptId: '0',
          formId: '',
          procName: '',
          procKey: ''
        }]
      },
      // 流程地址
      getProcessListURL: '/act/process/list',
      // 流程数据
      processData: [{
        key: '',
        name: ''
      }],
      // 部门列表
      deptList: [],
      /** 单选 */
      selectParams: {
        multiple: false,
        clearable: true,
        placeholder: '请选择部门'
      },
      treeParams: {
        clickParent: true,
        filterable: false,
        props: {
          children: 'children',
          label: 'name',
          value: 'id',
          disabled: 'disabled'
        }
      }
    }
  },
  computed: {
    dataRule () {
      return {
        procKey: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    show (row) {
      this.processVisible = true
      // 等待DOM完成更新 v-if 渲染后执行
      this.$nextTick(() => {
        this.defaultRow = row
        this.$refs.process1.defaultValues = row.procKey ? [{ key: row.procKey, name: row.procName }] : []
        this.$refs.process1.init()
      })
    },
    backFun (data) {
      let row = this.defaultRow
      if (data && data[0]) {
        row.procKey = data[0].key
        row.procName = data[0].name
        row.formId = this.formId
      } else {
        row.procKey = null
        row.procName = null
        row.formId = null
      }
    },
    init () {
      this.$nextTick(() => {
        this.loading = true
        this.$refs['dataForm'].resetFields()
        // 初始化数组
        this.dataForm.models = [{
          id: '',
          deptId: '0',
          formId: '',
          procName: '',
          procKey: ''
        }]
        // 获取流程
        // this.getProcess()
        // 获取部门
        this.getDeptList()
        // 获取配置
        this.getInfo()
      })
    },
    // 获取信息
    getInfo () {
      this.$http.get(`/flowable/bpmFormProc/form/${this.formId}`
      ).then(({ data: res }) => {
        this.loading = false
        if (res.code !== 0) {
          return
        }
        if (res.data.models.length) {
          this.dataForm = res.data
        }
      }).catch(() => { })
    },
    // 获取流程列表
    getProcess () {
      this.$http.get(this.getProcessListURL, { params: { hasDeploy: '0' } }).then(({ data: res }) => {
        if (res.code !== 0) {
          return
        }
        this.processData = res.data
      }).catch(() => { })
    },
    // 获取部门列表
    getDeptList () {
      return this.$http.get('/sys/dept/list').then(({ data: res }) => {
        if (res.code !== 0) {
          return
        }
        this.deptList = this.$utils.treeDataTranslate(res.data)
      }).catch(() => { })
    },
    // 添加规则
    addModel () {
      this.dataForm.models.push({
        id: '',
        formId: '',
        deptId: '',
        procName: '',
        procKey: ''
      })
    },
    // 移除规则
    removeModel (item) {
      var index = this.dataForm.models.indexOf(item)
      if (index !== -1) {
        this.dataForm.models.splice(index, 1)
      }
    },
    // select选择回调
    processChange (key, model) {
      let obj = {}
      obj = this.processData.filter(item => (item['key'] || '').toString() === (key || '').toString())[0]
      model.procName = obj.name
      model.formId = this.formId
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      // 检查参数是否合法
      for (let index = 0; index < this.dataForm.models.length; index++) {
        const element = this.dataForm.models[index]
        if (!element.deptId) {
          return this.$message.error('部门不允许为空')
        }
        // 判断部门是否重复
        for (let index1 = 0; index1 < this.dataForm.models.length; index1++) {
          if (index !== index1 && element.deptId === this.dataForm.models[index1].deptId) {
            return this.$message.error('部门重复')
          }
        }
        if (!element.procKey) {
          return this.$message.error('流程实例不允许为空')
        }
      }
      // 提交信息
      this.$http[!this.dataForm.models[0].id ? 'post' : 'put']('/flowable/bpmFormProc', this.dataForm).then(({ data: res }) => {
        if (res.code !== 0) {
          return
        }
        this.$message({
          message: this.$t('prompt.success'),
          type: 'success',
          duration: 500,
          onClose: () => {
            this.$emit('refreshNextData')
          }
        })
      }).catch(() => { })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>
